import axios from "axios";
import { MessageBox,Message } from "element-ui";

const http = axios.create({
    baseURL:'/admin-api',//接口的基础url
    timeout:5000,

})

//对请求进行拦截
http.interceptors.request.use(config => {
        let token = localStorage.getItem('login-token')
        if(token){
            config.headers['Authorization']='Bearer' + token //jwt认证的令牌
        }
        return config
    },error => {
        console.log(error)
        Promise.reject(error)
})  

http.interceptors.response.use(response=>{
        let res = response.data
        console.log('---------------------------------',res)
        if(200 == res.code){//状态码表示响应数据成功
            return res
        }
        if(401 == res.code){
            MessageBox.confirm("您没有登录或者登录失效",'提示',{
                //跳转到登录
                cancelButtonText:'取消',
                confirmButtonText:'确定',
                type:'warning'
            }).then(()=>{
                localStorage.removeItem('login-token')
                window.location.href = '/login'
            }).catch(err=>{
                console.log("点击取消")
            })
        }else{
            Message({
                type:'error',
                message:res.msg ? res.msg : '错误',
                duration:2000
            })
        }
        if(403 == res.code){
            MessageBox.confirm("您权限不足",'提示',{
                //跳转到登录
                cancelButtonText:'取消',
                confirmButtonText:'确定',
                type:'warning'
            }).then(()=>{
                localStorage.removeItem('login-token')
                window.location.href = '/login'
            }).catch(err=>{
                console.log("点击取消")
            })
        }else{
            Message({
                type:'error',
                message:res.msg ? res.msg : '错误',
                duration:2000
            })
        }
        return Promise.reject(new Error(res.msg ? res.msg : '错误'))
    },error=>{

        console.log(error)
        Message({
            type:'error',
            message:error.msg ? error.msg : '错误',
            duration:200
        })
        return Promise.reject(error)
})

export default http